package cn.bellychang.endpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.PublicMetrics;
import org.springframework.boot.actuate.metrics.Metric;
import org.springframework.stereotype.Component;

import javax.management.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Set;

/**
 * @author ChangLiang
 * @date 2020/3/21
 */
@Component
public class QueueCountEndpoint implements PublicMetrics {

    @Autowired
    private MBeanServer mBeanServer;


    @Override
    public Collection<Metric<?>> metrics() {
        Collection<Metric<?>> result = new ArrayList<>();
        try {
            Set<ObjectName> objectNames = mBeanServer.queryNames(new ObjectName("metrics:name=queue-counter,*"), null);
            if (objectNames != null && objectNames.size() == 1) {
                for (ObjectName objectName : objectNames) {
                    Long count = (Long) mBeanServer.getAttribute(objectName, "Count");
                    result.add(new Metric<Number>("queue-counter", count, new Date()));
                }
            }
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        } catch (AttributeNotFoundException e) {
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            e.printStackTrace();
        } catch (ReflectionException e) {
            e.printStackTrace();
        } catch (MBeanException e) {
            e.printStackTrace();
        }
        return result;
    }
}
